package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户表服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public PageResponse<UserVo> selectUserPage(Integer pageNum, Integer pageSize, UserDto userDto) {
        // 查询用户基本信息列表
        PageHelper.startPage(pageNum, pageSize);
        userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        Page<UserVo> page = userMapper.findByCondition(userDto);
        if (CollectionUtil.isEmpty(page.getResult())) {
            return PageResponse.of(page, UserVo.class);
        }
        //查询用户角色信息
        List<Long> userIds = page.getResult().stream().map(UserVo::getId).collect(Collectors.toList());
        List<RoleVo> roleVoList = userRoleMapper.queryByUserIds(userIds);
        Map<String, List<RoleVo>> roleMap = roleVoList.stream().collect(Collectors.groupingBy(RoleVo::getUserId));
        //为每一个用户设置角色信息
        page.getResult().stream().forEach(userVo -> {
            Long id = userVo.getId();
            List<RoleVo> userRoleList = roleMap.getOrDefault(id.toString(), Collections.emptyList());
            Map<String, String> map = userRoleList.stream().collect(Collectors.toMap(roleVo -> roleVo.getId().toString(), roleVo -> roleVo.getRoleName()));
            userVo.setRoleVoIds(map.keySet());
            userVo.setRoleLabels(map.values().stream().collect(Collectors.toSet()));
        });

        return PageResponse.of(page, UserVo.class);
    }

    @Override
    @Transactional
    public void addUser(UserDto userDto) {
        // 保存用户基本信息
        User user = BeanUtil.toBean(userDto, User.class);
        user.setUsername(user.getEmail());
        user.setPassword(BCrypt.hashpw(SuperConstant.INIT_PASSWORD));
        user.setUserType("0");
        user.setDataState(SuperConstant.DATA_STATE_0);
        user.setIsDelete(SuperConstant.IS_DELETE_0);
        user.setIsLeader(SuperConstant.IS_LEADER_0);

        userMapper.insert(user);
        // 保存用户和职位关联信息
        Set<String> roleVoIds = userDto.getRoleVoIds();
        if (CollectionUtil.isEmpty(roleVoIds)) {
            return;
        }
        List<UserRole> userRoleList = roleVoIds.stream().map(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setRoleId(Long.valueOf(roleId));
            userRole.setUserId(user.getId());
            userRole.setDataState(SuperConstant.DATA_STATE_0);
            return userRole;
        }).collect(Collectors.toList());
        userRoleMapper.insertBatch(userRoleList);
    }

    @Override
    public void updateUser(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        User oldUser = userMapper.selectByPrimaryKey(user.getId());
        if (!oldUser.getEmail().equals(user.getEmail())){
            System.out.println("该用户需要重新登录");
        }
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void updateUserDataState(Long id, String status) {
        User user = userMapper.selectByPrimaryKey(id);
        user.setDataState(status);
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public boolean deleteUser(String userIds) {
        Long id = Long.valueOf(userIds);
        User user = userMapper.selectByPrimaryKey(id);
        if (user.getDataState().equals(SuperConstant.DATA_STATE_0)) {
            return false;
        }
        userMapper.deleteUser(id);
        return true;
    }

    @Override
    public void resetPasswords(Long userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        user.setPassword(BCrypt.hashpw(SuperConstant.INIT_PASSWORD));
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public List<UserVo> selectAllUser(UserDto userDto) {
        List<User> userList = userMapper.selectAllUser();
        return BeanUtil.copyToList(userList, UserVo.class);
    }
}
